<?php 
defined('RUN_KATANA') or die('Restricted access');
require(CORE_CONFIG_PATH.'shop.php');
require(MODEL_INCLUDE_PATH.'shop/product.php');
require(MODEL_INCLUDE_PATH.'shop/productVariation.php');
require(MODEL_INCLUDE_PATH.'shop/productAttribute.php');
require(MODEL_INCLUDE_PATH.'shop/productAttributeValue.php');
require(MODEL_INCLUDE_PATH.'shop/productGroup.php');
require(MODEL_INCLUDE_PATH.'shop/productCat.php');
require(MODEL_INCLUDE_PATH.'shop/productBrand.php');
require(MODEL_INCLUDE_PATH.'shop/provider.php');
require(MODEL_INCLUDE_PATH.'shop/orderItem.php');
require(MODEL_INCLUDE_PATH.'shop/cart.php');
require(MODEL_INCLUDE_PATH.'shop/order.php');
require(MODEL_INCLUDE_PATH.'shop/payment.php');
require(MODEL_INCLUDE_PATH.'shop/shipping.php');
require(MODEL_INCLUDE_PATH.'shop/payments/dibs.php');
require(MODEL_INCLUDE_PATH.'shop/payments/nets.php');
require(MODEL_INCLUDE_PATH.'shop/shopQuestion.php');
require(MODEL_INCLUDE_PATH.'shop/shopQuestionAnswer.php');
require(MODEL_INCLUDE_PATH.'shop/shopQuestionResponse.php');
class ShopController extends ObjectController
{
	public 	$SiteId;
	/* List view variables */
	public 	$MenuId;
	public 	$CatId;
	public 	$GroupId;
	public 	$ProductList;
	public 	$ProductListOrderBy;
	public 	$ProductListLimit;
	/* List view variables End */
	
	/* Detail view variables */
	public 	$CurrentProduct;
	public 	$CurrentProductId;
	/* Detail view variables End*/
	
	/* ProductAttributes */ 
	public 	$Attributes;
	public 	$ProductAttributes;
	public 	$ProductAttributesLoaded;
	public 	$CurrentAttribute;
	public 	$CurrentAttributeId;
	/* ProductAttributes End*/ 
	
	/* Orders */
	public 	$Orders;
	public 	$OrdersNew;
	public 	$OrdersPending;
	public 	$OrdersProcessed;
	public 	$OrdersLoaded;
	public 	$CurrentOrderId;
	public 	$CurrentOrder;
	/* Orders End*/
	
	/* ShopQuestion */
	public 	$ShopQuestions;
	/* ShopQuestion End*/
	
	/* ShopProviders */ 
	public 	$Providers;
	public 	$CurrentProvider;
	public 	$CurrentProviderId;
	/* ShopProviders End*/ 
	
	/* ShopGroups */ 
	public 	$Groups;
	public 	$CurrentGroup;
	public 	$CurrentGroupId;
	/* ShopGroups End*/ 
	
	public 	$GlobalSettings;
	public 	$Forms;
	public 	$Cats;
	public 	$Brands;
	public 	$BrandProviders;
	public 	$ShippingMethods;
	public 	$ShippingZones;
	public 	$TaxGroups;
	public  $Currencies;
	
	public function ShopController($pageId=0, $catId=0, $groupId=0) 
	{
		global $katana;
		self::setSiteId($katana->getId());
		self::loadSettings();
		if($pageId > 0)
		{ self::setMenuId($siteId); }
		else
		{
			if(intval($_REQUEST['m']) > 0)
			{ self::setMenuId(intval($_REQUEST['m'])); }
			else
			{
				if($katana->viewFrontpage())
				{ self::setMenuId(1); }
			}
		}
		if(intval($_REQUEST['p']) > 0)
		{ 
			self::setCurrentProductId(intval($_REQUEST['p']));
			self::setViewObject('Product');
		}
		if($catId > 0)
		{ self::setCatId($catId); }
		if($groupId > 0)
		{ self::setGroupId($groupId); }
		self::setOrdersLoaded(false);
		self::setProductAttributesLoaded(false);
		
		if(intval($_REQUEST['orderid']) > 0)
		{ self::setCurrentOrderId(intval($_REQUEST['orderid'])); }
	}
	
	/* Get Functions */ 
	public function getSiteId() { return intval($this->SiteId); } 
	/* List view variables */
	public function getMenuId() { return intval($this->MenuId); }
	public function getCatId() { return intval($this->CatId); }
	public function getGroupId() { return intval($this->GroupId); }
	public function getProductList() { return $this->ProductList; }
	public function getProductListOrderBy() { return $this->ProductListOrderBy; }
	public function getProductListLimit() { return $this->ProductListLimit; }
	/* List view variables End */
	
	/* Detail view variables */
	public function getCurrentProduct($id=0) 
	{ 
		if((!($this->CurrentProduct)) && (self::getCurrentProductId() > 0))
		{
			if(($id > 0) && ($id != self::getCurrentProductId()))
			{ self::setCurrentProductId($id); }
			self::loadCurrentProduct(); 
		}
		return $this->CurrentProduct; 
	}
	public function getCurrentProductId() { return $this->CurrentProductId; }
	/* Detail view variables End*/
	
	/* Orders */
	public function getOrder($id=0)
	{ 
		if($id > 0)
		{
			self::loadOrders($id);
			if(is_object($this->Orders[$id]))
			{ return $this->Orders[$id]; }
		}
	}
	public function getOrders() 
	{ 
		self::loadOrders();
		return $this->Orders; 
	}
	public function getOrdersNew() 
	{ 
		self::loadOrders();
		return $this->OrdersNew; 
	}
	public function getOrdersNewCount() 
	{ 
		self::loadOrders();
		return count($this->OrdersNew); 
	}
	public function getOrdersPending() 
	{ 
		self::loadOrders();
		return $this->OrdersPending; 
	}
	public function getOrdersPendingCount() 
	{ 
		self::loadOrders();
		return count($this->OrdersPending); 
	}
	public function getOrdersProcessed() 
	{ 
		self::loadOrders();
		return $this->OrdersProcessed; 
	}
	public function getOrdersProcessedCount() 
	{ 
		self::loadOrders();
		return count($this->OrdersProcessed); 
	}
	public function getCurrentOrder() 
	{ 
		if(is_object($this->CurrentOrder))
		{ return $this->CurrentOrder; } 
		else
		{
			if(self::getCurrentOrderId() > 0)
			{
				if(is_object(self::getOrder(self::getCurrentOrderId())))
				{ return $this->CurrentOrder; }
			}
		}
	}
	public function getCurrentOrderId() { return intval($this->CurrentOrderId); }
	public function getOrdersLoaded() { return $this->OrdersLoaded; }
	/* Orders End*/
	
	public function getGlobalSettings() 
	{ return self::getSettings(); }
	public function getGlobalSetting($setting='') 
	{ return self::getSetting($setting); }
	
	/* Shop Attributes */
	public function getAttributes() 
	{ 
		if(!($this->Attributes))
		{ self::setAttributes(); }
		return $this->Attributes; 
	}
	public function getProductAttribute($id=0) 
	{ 
		if($id > 0)
		{
			self::loadProductAttributes();
			return $this->ProductAttributes[$id]; 
		}
	}
	public function getProductAttributes() 
	{ 
		self::loadProductAttributes();
		return $this->ProductAttributes; 
	}
	public function getCurrentAttribute() { return $this->CurrentAttribute; }
	public function getCurrentAttributeId() { return $this->CurrentAttributeId; }
	public function getProductAttributesLoaded() { return $this->ProductAttributesLoaded; }
	/* Shop Attributes End */
	/* ShopProviders */ 
	public function getProvider($id=0) 
	{ 
		if($id > 0)
		{
			self::loadProviders();
			if(is_object($this->Providers[$id]))
			{ return $this->Providers[$id]; }
		}
	}
	public function getProviders() 
	{ 
		self::loadProviders();
		return $this->Providers; 
	}
	public function getCurrentProvider()
	{ 
		if((!(is_object($this->CurrentProvider))) && (self::getCurrentProviderId() > 0))
		{ self::loadProviders(self::getCurrentProviderId()); }
		return $this->CurrentProvider; 
	}
	public function getCurrentProviderId() { return $this->CurrentProviderId; }
	/* ShopProviders End*/ 
	
	/* ShopQuestions */ 
	public function getShopQuestions() 
	{ 
		self::loadShopQuestions();
		return $this->ShopQuestions; 
	}
	/* ShopQuestions End*/ 
	
	/* ShopBrands */ 
	public function getBrand($id=0) 
	{ 
		if($id > 0)
		{
			self::loadBrands();
			if(is_object($this->Brands[$id]))
			{ return $this->Brands[$id]; }
		}
	}
	public function getBrands() 
	{ 
		self::loadBrands();
		return $this->Brands; 
	}
	/* ShopBrands End*/ 
	/* ShopBrandProviders */ 
	public function getBrandProvider($id=0) 
	{ 
		if($id > 0)
		{
			self::loadBrandProviders();
			if(is_object($this->BrandProviders[$id]))
			{ return $this->BrandProviders[$id]; }
		}
	}
	public function getBrandProviders()
	{ 
		self::loadBrandProviders();
		return $this->BrandProviders; 
	}
	/* ShopBrandProviders End*/ 
	/* ShopCats */
	public function getCat($id=0) 
	{ 
		if($id > 0)
		{
			self::loadCats();
			if(is_object($this->Cats[$id]))
			{ return $this->Cats[$id]; }
		}
	}
	public function getCats() 
	{ 
		self::loadCats();
		return $this->Cats; 
	}
	/* ShopCats End*/
	/* ShopGroups */ 
	public function getGroup($id=0) 
	{ 
		if($id > 0)
		{
			self::loadGroups();
			if(is_object($this->Groups[$id]))
			{ return $this->Groups[$id]; }
		}
	}
	public function getGroups() 
	{ 
		self::loadGroups();
		return $this->Groups; 
	}
	public function getCurrentGroup()
	{ 
		if((!(is_object($this->CurrentGroup))) && (self::getCurrentGroupId() > 0))
		{ self::loadGroups(self::getCurrentGroupId()); }
		return $this->CurrentGroup; 
	}
	public function getCurrentGroupId() { return $this->CurrentGroupId; }
	/* ShopGroups End*/ 
	
	public function getTaxGroups($id=0) 
	{ 
		if(!($this->TaxGroups))
		{ self::loadTaxGroups(); }
		return $this->TaxGroups; 
	}
	
	public function getTaxGroup($id=0) 
	{ 
		if($id > 0)
		{
			if(isset($this->TaxGroups[$id]))
			{ return $this->TaxGroups[$id]; }
			else
			{
				if(!($this->TaxGroups))
				{ self::loadTaxGroups(); }
				
				if(isset($this->TaxGroups[$id]))
				{ return $this->TaxGroups[$id]; }
				else
				{ return; } 
			}
		}
	}
	
	public function getTaxGroupTax($id=0) 
	{ 
		if($id > 0)
		{
			if(isset($this->TaxGroups[$id]))
			{ return $this->TaxGroups[$id]['tax']; }
			else
			{
				if(!($this->TaxGroups))
				{ self::loadTaxGroups(); }
				
				if(isset($this->TaxGroups[$id]))
				{ return $this->TaxGroups[$id]['tax']; }
				else
				{ return 1; } 
			}
		}
	}
	
	public function getCurrencies() 
	{ 
		if(!($this->Currencies))
		{ self::loadCurrencies(); }
		return $this->Currencies; 
	}
	
	public function getCurrency($iso='') 
	{ 
		if($iso != '')
		{
			if(isset($this->Currencies[$iso]))
			{ return $this->Currencies[$iso]; }
			else
			{
				if(!($this->Currencies))
				{ self::loadCurrencies(); }
				
				if(isset($this->Currencies[$iso]))
				{ return $this->Currencies[$iso]; }
				else
				{ return; } 
			}
		}
	}
	
	public function getCurrencyUnit($iso='') 
	{ 
		if($iso != '')
		{
			if(isset($this->Currencies[$id]))
			{ return $this->Currencies[$id]['unit']; }
			else
			{
				if(!($this->Currencies))
				{ self::loadCurrencies(); }
				
				if(isset($this->Currencies[$id]))
				{ return $this->Currencies[$id]['unit']; }
				else
				{ return 0; }
			}
		}
	}
	
	public function getCurrencyValue($iso='') 
	{ 
		if($iso != '')
		{
			if(isset($this->Currencies[$id]))
			{ return $this->Currencies[$id]['value']; }
			else
			{
				if(!($this->Currencies))
				{ self::loadCurrencies(); }
				
				if(isset($this->Currencies[$id]))
				{ return $this->Currencies[$id]['value']; }
				else
				{ return 1; }
			}
		}
	}
	
	public function getDefaultCurrency() 
	{ 
		if(!($this->Currencies))
		{ self::loadCurrencies(); }
		if(count($this->Currencies) > 0)
		{
			foreach($this->Currencies as $cur)
			{
				if($cur['isDefault'] > 0)
				{ return $cur; }
			}
		}
	}
	
	function convertFromCurrency($amount=1, $from='EU', $decimals=2, $round=0) 
	{
		if(($amount > 0) && ($from != ''))
		{
			$fromCurrency = self::getCurrency($from);
			$convAmmount = 0;
			
			if(is_array($fromCurrency))
			{ $convAmmount = ($fromCurrency['value'] / $fromCurrency['unit']) * $amount; }
			return number_format(round($convAmmount, $decimals), $decimals, '.', '');
		}
   	}

	function convertToCurrency($amount=1, $to='EU', $decimals=2, $round=0) 
	{
		if(($amount > 0) && ($to != ''))
		{
			$toCurrency = self::getCurrency($to);
			$convAmmount = 0;
			
			if(is_array($toCurrency))
			{ $convAmmount = ($amount / $toCurrency['value']) * $toCurrency['unit']; }
			return number_format(round($convAmmount, $decimals), $decimals, '.', '');
		}
   	}

	public function getShippingMethods() 
	{ 
		if(!($this->ShippingMethods))
		{ self::setShippingMethods(); }
		return $this->ShippingMethods; 
	}
	
	public function getShippingZones($parent=0) 
	{ 
		self::loadShippingZones(0, $parent);
		return $this->ShippingZones;
	}
	
	public function getForms($key='')
	{
		if($key != '')
		{
			if(!($this->Forms[$key]))
			{ self::setForms($key); }
			return $this->Forms[$key];
		}
	}
	
	/* Set Functions */ 
	public function setSiteId($val) { $this->SiteId=intval($val); } 
	/* List view variables */
	public function setMenuId($val) { $this->MenuId=intval($val); } 
	public function setCatId($val) { $this->CatId=intval($val); } 
	public function setGroupId($val) { $this->GroupId=intval($val); } 
	public function setProductList($val) { $this->ProductList=$val; }
	public function setProductListOrderBy($val) { $this->ProductListOrderBy=$val; }
	public function setProductListLimit($val) { $this->ProductListLimit=$val; }
	/* List view variables end */
	/* Detail view variables */
	public function setCurrentProduct($val) { $this->CurrentProduct=$val; }
	public function setCurrentProductId($val) { $this->CurrentProductId=$val; }
	/* Detail view variables End*/
	/* Orders */
	public function setOrders($val) { $this->Orders=$val; }
	public function setOrdersNew($val) { $this->OrdersNew=$val; }
	public function setOrdersPending($val) { $this->OrdersPending=$val; }
	public function setOrdersProcessed($val) { $this->OrdersProcessed=$val; }
	public function setOrdersLoaded($val) { $this->OrdersLoaded=$val; }
	public function setCurrentOrderId($val) { $this->CurrentOrderId=intval($val); }
	/* Orders End*/
	
	public function setAttributes() { $this->Attributes = self::loadProductAttributes(); } 
	/* Shop Attributes */
	//public function setAttributes($val) { $this->OrdersLoaded=$val; }
	public function setProductAttributes($val) { $this->ProductAttributes=$val; }
	public function setCurrentAttribute($val) { $this->CurrentAttribute=$val; }
	public function setCurrentAttributeId($val) { $this->CurrentAttributeId=$val; }
	public function setProductAttributesLoaded($val) { $this->ProductAttributesLoaded=$val; }
	/* Shop Attributes End */
	
	/* Shop Providers */
	public function setProviders($val) { $this->Providers = $val; } 
	public function setCurrentProvider($val) { $this->CurrentProvider=$val; }
	public function setCurrentProviderId($val) { $this->CurrentProviderId=intval($val); }
	/* Shop Providers End */
	
	/* Shop Groups */
	public function setGroups() { $this->Groups = $val; } 
	public function setCurrentGroup($val) { $this->CurrentGroup=$val; }
	public function setCurrentGroupId($val) { $this->CurrentGroupId=intval($val); }
	/* Shop Groups End */
	
	public function setCats() { $this->Cats = $val; } 
	public function setBrands($val) { $this->Brands = $val; }
	public function setBrandProviders($val) { $this->BrandProviders = $val; } 
	public function setShippingMethods() { $this->ShippingMethods = self::getShopShippingMethods(); }
	public function setShippingZones() { $this->ShippingZones = self::getShopShippingZones(); }
	
	function loadSettings()
	{
		global $config;
		if(!self::getItemLoaded('settings'))
		{ 
			$this->Settings = $config['shop'];
			$this->GlobalSettings = $config['shop'];
			
			if($this->GlobalSettings['favourite_pickup_locations'] == true)
			{
				if(intval($_REQUEST['fav_store']) > 0)
				{
					if(intval($_COOKIE['fav_store']) != intval($_REQUEST['fav_store']))
					{ setcookie('fav_store', '', time()-3600, '/'); }
					
					$expire=time()+60*60*24*30;
					setcookie('fav_store', intval($_REQUEST['fav_store']), $expire, '/'); 
				}
			}
			
			self::setItemLoaded('settings', true);
		}
	}
	
	function loadCurrentProduct($loadVariations = true)
	{
		if(self::getCurrentProductId() > 0)
		{	
			global $db;
			//echo '<br />loadCurrentProduct<br />MemmoryUsage:'.memory_get_usage();
			$sql  = 'SELECT ';
			/* Product */
			$sql .= 'p.*, ';
			$sql .= 'smp.title AS SectionTitle, ';
			
			/* Product Variation */
			$sql .= 'pv.id AS variation_id, ';
			$sql .= 'pv.product_id, ';
			$sql .= 'pv.varnum, ';
			$sql .= 'pv.var_title, ';
			$sql .= 'pv.active as vActive, ';
			$sql .= 'pv.identity, ';
			$sql .= 'pv.ext_identity, ';
			$sql .= 'pv.buy_min, ';
			$sql .= 'pv.stock_count, ';
			$sql .= 'pv.stock_add_date, ';
			$sql .= 'pv.stock_add_quan, ';
			$sql .= 'pv.stock_add_txt, ';
			$sql .= 'pv.net_weight, ';
			$sql .= 'pv.gros_weight, ';
			$sql .= 'pv.length, ';
			$sql .= 'pv.width, ';
			$sql .= 'pv.height, ';
			$sql .= 'pv.std_price, ';
			$sql .= 'pv.now_price, ';
			$sql .= 'pv.NowPriceDateEnd, ';
			$sql .= 'pv.offer_price, ';
			$sql .= 'pv.offer_start, ';
			$sql .= 'pv.offer_end, ';
			
			$sql .= 'pcat.title as cat_title, pgrp.title as group_title, brands.title as brand_title FROM '.DB_PERFIX.'product AS p  ';
			$sql .= 'LEFT JOIN '.DB_PERFIX.'product_vars AS pv ON p.id=pv.product_id ';
			$sql .= 'LEFT JOIN '.DB_PERFIX.'sitemap_pages AS smp ON p.section_id=smp.id ';
			$sql .= 'LEFT JOIN '.DB_PERFIX.'product_cats AS pcat ON p.cat_id=pcat.id ';
			$sql .= 'LEFT JOIN '.DB_PERFIX.'product_groups AS pgrp ON p.group_id=pgrp.id ';
			$sql .= 'LEFT JOIN '.DB_PERFIX.'product_brands AS brands ON p.brand=brands.id ';
			$sql .= 'WHERE p.id='.self::getCurrentProductId().' AND pv.varnum=1 LIMIT 1;';
			
			$result = $db->query($sql);
			$data = $db->fetch($sql, CACHE_TTL);
			
			if(is_array($data))
			{
				foreach($data as $row)
				{
					self::setCurrentProductId($row['id']);
					$this->CurrentProduct = new Product;
					$this->CurrentProduct->setId($row['id']);
					$this->CurrentProduct->setTitle($row['title']);
					$this->CurrentProduct->setAlias($row['alias']);
					$this->CurrentProduct->setSectionId($row['section_id']);
					$this->CurrentProduct->setSectionTitle($row['SectionTitle']);
					$this->CurrentProduct->setCatId($row['cat_id']);
					$this->CurrentProduct->setCatTitle($row['cat_title']);
					$this->CurrentProduct->setGroupId($row['group_id']);
					$this->CurrentProduct->setGroupTitle($row['group_title']);
					$this->CurrentProduct->setBrand($row['brand']);
					$this->CurrentProduct->setBrandTitle($row['brand_title']);
					$this->CurrentProduct->setProvider($row['provider']);
					$this->CurrentProduct->setFrontpageDisplay($row['FrontpageDisplay']);
					$this->CurrentProduct->setTaxId($row['tax_id']);
					$this->CurrentProduct->setTaxValue(self::getTaxGroupTax($row['tax_id']));
					$this->CurrentProduct->setIntro($row['intro']);
					$this->CurrentProduct->setDescription($row['Description']);
					$this->CurrentProduct->setDetails($row['details']);
					$this->CurrentProduct->setHasImage($row['has_image']);
					$this->CurrentProduct->setPrice($row['price']);
					$this->CurrentProduct->setProductOrder($row['product_order']);
					$this->CurrentProduct->setSaleStartHour($row['SaleStartHour']);
					$this->CurrentProduct->setSaleEndHour($row['SaleEndHour']);
					$this->CurrentProduct->setStockUnit($row['stock_unit']);
					$this->CurrentProduct->setWeightUnit($row['weight_unit']);
					$this->CurrentProduct->setDimUnit($row['dim_unit']);
					$this->CurrentProduct->setDateCreated($row['date_created']);
					$this->CurrentProduct->setDateModified($row['date_modified']);
					$this->CurrentProduct->setActive($row['active']);
					$this->CurrentProduct->setActiveStart($row['active_start']);
					$this->CurrentProduct->setActiveEnd($row['active_end']);
					$this->CurrentProduct->setViews($row['views']);
					$this->CurrentProduct->setView(self::getView());
					
					/* Set first variation */
					$this->CurrentProduct->setFirstVariationId($row['variation_id']);
					$this->CurrentProduct->setCurrentVariationId($row['variation_id']);
					$this->CurrentProduct->setCurrentVariationNum($row['varnum']);
					
					//echo '<br />loadAttributest<br />MemmoryUsageB4:'.memory_get_usage();
					$this->CurrentProduct->loadAttributes();
					//echo '<br />loadedAttributes<br />MemmoryUsageAF:'.memory_get_usage();
					
					$this->CurrentProduct->Variations[$row['variation_id']] = new ProductVariation;
					$this->CurrentProduct->Variations[$row['variation_id']]->setId($row['variation_id']);
					$this->CurrentProduct->Variations[$row['variation_id']]->setProductId($this->CurrentProduct->getId());
					$this->CurrentProduct->Variations[$row['variation_id']]->setVarnum($row['varnum']);
					$this->CurrentProduct->Variations[$row['variation_id']]->setVarTitle($row['var_title']);
					$this->CurrentProduct->Variations[$row['variation_id']]->setActive($row['vActive']);
					$this->CurrentProduct->Variations[$row['variation_id']]->setIdentity($row['identity']);
					$this->CurrentProduct->Variations[$row['variation_id']]->setExtIdentity($row['ext_identity']);
					$this->CurrentProduct->Variations[$row['variation_id']]->setBuyMin($row['buy_min']);
					$this->CurrentProduct->Variations[$row['variation_id']]->setStockCount($row['stock_count']);
					$this->CurrentProduct->Variations[$row['variation_id']]->setStockAddDate($row['stock_add_date']);
					$this->CurrentProduct->Variations[$row['variation_id']]->setStockAddQuan($row['stock_add_quan']);
					$this->CurrentProduct->Variations[$row['variation_id']]->setStockAddTxt($row['stock_add_txt']);
					$this->CurrentProduct->Variations[$row['variation_id']]->setNetWeight($row['net_weight']);
					$this->CurrentProduct->Variations[$row['variation_id']]->setGrosWeight($row['gros_weight']);
					$this->CurrentProduct->Variations[$row['variation_id']]->setLength($row['length']);
					$this->CurrentProduct->Variations[$row['variation_id']]->setWidth($row['width']);
					$this->CurrentProduct->Variations[$row['variation_id']]->setHeight($row['height']);
					$this->CurrentProduct->Variations[$row['variation_id']]->setStdPrice($row['std_price']);
					$this->CurrentProduct->Variations[$row['variation_id']]->setNowPrice($row['now_price']);
					$this->CurrentProduct->Variations[$row['variation_id']]->setNowPriceDateEnd($row['NowPriceDateEnd']);
					$this->CurrentProduct->Variations[$row['variation_id']]->setOfferPrice($row['offer_price']);
					$this->CurrentProduct->Variations[$row['variation_id']]->setOfferStart($row['offer_start']);
					$this->CurrentProduct->Variations[$row['variation_id']]->setOfferEnd($row['offer_end']);
					$this->CurrentProduct->Variations[$row['variation_id']]->setTaxId($this->CurrentProduct->TaxId);
					$this->CurrentProduct->Variations[$row['variation_id']]->setTaxValue($this->CurrentProduct->TaxValue);
					
					if(count($this->CurrentProduct->AttributesVar) > 0)
					{ $this->CurrentProduct->Variations[$row['variation_id']]->setAttributes($this->CurrentProduct->AttributesVar); }
					
					/* Set first variation End */
					$this->CurrentProduct->setFirstVariationLoaded(true);
					//$this->CurrentProduct->loadImages();
					if($loadVariations)
					{ $this->CurrentProduct->loadVariations(); }
					//$this->CurrentProduct->loadAttributes();
				}
			}
			unset($data);
		}
	}
	
	function loadProductsList($orderby='')
	{
		$i=0;
		if((self::getMenuId() > 0) || (self::getCatId() > 0) || (self::getGroupId() > 0))
		{ 
			global $db;
			$select  = 'p.id, ';
			$select .= 'p.section_id, ';
			$select .= 'p.cat_id, ';
			$select .= 'p.group_id , ';
			$select .= 'p.brand, ';
			$select .= 'p.provider, ';
			$select .= 'p.title, ';
			$select .= 'p.alias, ';
			$select .= 'p.intro, ';
			$select .= 'p.has_image, ';
			$select .= 'p.price, ';
			$select .= 'p.tax_id, ';
			$select .= 'p.FrontpageDisplay, ';
			$select .= 'p.SaleStartHour, ';
			$select .= 'p.SaleEndHour, ';
			
			if(self::getFrontend() == 0)
			{
				$select .= 'p.Description, ';
				$select .= 'p.details, ';
				$select .= 'p.stock_unit, ';
				$select .= 'p.weight_unit, ';
				$select .= 'p.dim_unit, ';
				$select .= 'p.product_order, ';
				$select .= 'p.active, ';
				$select .= 'p.active_start, ';
				$select .= 'p.active_end, ';
				$select .= 'p.date_created, ';
				$select .= 'p.date_modified, ';
				$select .= 'p.views, ';
			}
			
			$select .= 'pvr.id AS variation_id, ';
			$select .= 'pvr.varnum, ';
			$select .= 'pvr.var_title, ';
			$select .= 'pvr.identity , ';
			$select .= 'pvr.ext_identity, ';
			$select .= 'pvr.buy_min, ';
			$select .= 'pvr.stock_count, ';
			$select .= 'pvr.std_price, ';
			$select .= 'pvr.now_price, ';
			$select .= 'pvr.NowPriceDateEnd, ';
			$select .= 'pvr.offer_price, ';
			$select .= 'pvr.offer_start, ';
			$select .= 'pvr.offer_end, ';
			
			$select .= 'pvr.length, ';
			$select .= 'pvr.width, ';
			$select .= 'pvr.height';
			
			if($this->View == 'frontend_list')
			{ $select .= ', img.image'; }
			$sql  = ' SELECT '.$select.' FROM '.DB_PERFIX.'product AS p  ';
			$sql .= ' LEFT JOIN '.DB_PERFIX.'product_vars AS pvr ON p.id=pvr.product_id ';
			if($this->View == 'frontend_list')
			{ $sql .= ' LEFT JOIN '.DB_PERFIX.'shop_images AS img ON (p.id=img.product_id AND img.default=1) '; }
			
			$sql .= ' LEFT JOIN '.DB_PERFIX.'sitemap_pages AS smp ON p.section_id=smp.id ';
			
			$sql .= ' WHERE (';
							 
			$sql .= ' p.section_id='.$this->MenuId.' OR p.id IN(SELECT product_id FROM '.DB_PERFIX.'product_to_menu WHERE menu_id='.$this->MenuId.') ';
			if($this->MenuId == 1)
			{ $sql .= ' OR p.FrontpageDisplay=1 '; }
			
			$sql .= ') ';
			
			$sql .= ' AND pvr.varnum=1 ';
			if(($this->View != 'commander_list') || ($this->View == 'frontend_list'))
			{ $sql .= ' AND p.active=1 '; }
			
			if(self::getCatId() > 0)
			{ $sql .= ' AND p.cat_id='.self::getCatId().' '; }
			if(self::getGroupId() > 0)
			{ $sql .= ' AND p.group_id='.self::getGroupId().' '; }
			
			if($this->MenuId == 1)
			{  
				$sql .= ' ORDER BY smp.menu_order ASC, p.product_order ASC';
			}
			else
			{
				if($this->ProductListOrderBy != '')
				{ $sql .= ' ORDER BY p.section_id ASC, '.$this->ProductListOrderBy; }
				else
				{ $sql .= ' ORDER BY p.section_id ASC, p.product_order ASC'; }
			}
			if(intval($this->ProductListLimit) > 0)
			{ $sql .= ' LIMIT '.intval($this->ProductListLimit); }
			else
			{ $sql .= ' LIMIT 100'; }
			
			
			
			$sql .= ';';
			
			$result = $db->query($sql);
			$data = $db->fetch($sql, self::getTTL());
/*
			global $user;
			if($user->getId() == 1)
			{
				echo $sql;
			}
*/
			if(is_array($data))
			{
				$cats 		= self::getCats();
				$groups		= self::getGroups();
				$brands 	= self::getBrands();
				$i = 0;
				foreach($data as $row)
				{
					$this->ProductList[$row['id']] = new Product;
					$this->ProductList[$row['id']]->setId($row['id']);
					$this->ProductList[$row['id']]->setTitle($row['title']);
					$this->ProductList[$row['id']]->setAlias($row['alias']);
					$this->ProductList[$row['id']]->setSectionId($row['section_id']);
					$this->ProductList[$row['id']]->setCatId($row['cat_id']);
					$this->ProductList[$row['id']]->setGroupId($row['group_id']);
					$this->ProductList[$row['id']]->setBrand($row['brand']);
					$this->ProductList[$row['id']]->setProvider($row['provider']);
					$this->ProductList[$row['id']]->setFrontpageDisplay($row['FrontpageDisplay']);
					$this->ProductList[$row['id']]->setTaxId($row['tax_id']);
					$this->ProductList[$row['id']]->setTaxValue(self::getTaxGroupTax($row['tax_id']));
					
					$this->ProductList[$row['id']]->setSaleStartHour($row['SaleStartHour']);
					$this->ProductList[$row['id']]->setSaleEndHour($row['SaleEndHour']);
					
					$this->ProductList[$row['id']]->setIntro($row['intro']);
					$this->ProductList[$row['id']]->setDetails($row['details']);
					$this->ProductList[$row['id']]->setHasImage($row['has_image']);
					$this->ProductList[$row['id']]->setPrice($row['price']);
					if($this->View == 'commander_list')
					{ $this->ProductList[$row['id']]->setProductOrder($i); }
					else
					{ $this->ProductList[$row['id']]->setProductOrder($row['product_order']); }
					
					$this->ProductList[$row['id']]->setStockUnit($row['stock_unit']);
					$this->ProductList[$row['id']]->setWeightUnit($row['weight_unit']);
					$this->ProductList[$row['id']]->setDimUnit($row['dim_unit']);
					$this->ProductList[$row['id']]->setDateCreated($row['date_created']);
					$this->ProductList[$row['id']]->setDateModified($row['date_modified']);
					$this->ProductList[$row['id']]->setActive($row['active']);
					$this->ProductList[$row['id']]->setActiveStart($row['active_start']);
					$this->ProductList[$row['id']]->setActiveEnd($row['active_end']);
					$this->ProductList[$row['id']]->setViews($row['views']);
				
					if(is_object($cats[$row['cat_id']]))
					{ $this->ProductList[$row['id']]->setCatTitle($cats[$row['cat_id']]->getTitle()); }
					if(is_object($groups[$row['group_id']]))
					{ $this->ProductList[$row['id']]->setGroupTitle($groups[$row['group_id']]->getTitle()); }
					if(is_object($brands[$row['brand']]))
					{ $this->ProductList[$row['id']]->setBrandTitle($brands[$row['brand']]->getTitle()); }
					$this->ProductList[$row['id']]->setListViewImage($row['image']);
					$this->ProductList[$row['id']]->setView($this->View);
					
					if($this->ProductList[$row['id']]->getListViewImage() != '')
					{
						$this->ProductList[$row['id']]->ImageObject = new Image();
						$this->ProductList[$row['id']]->ImageObject->setId(0);
						$this->ProductList[$row['id']]->ImageObject->setDataTable('shop_images');
						$this->ProductList[$row['id']]->ImageObject->setParentIdField('product_id');
						$this->ProductList[$row['id']]->ImageObject->setParentId($row['id']);
						$this->ProductList[$row['id']]->ImageObject->setFolderPath(PRODUCT_PATH);
						$this->ProductList[$row['id']]->ImageObject->setFolderUrl(PRODUCT_URL);
						$this->ProductList[$row['id']]->ImageObject->setFilename($row['image']);
					}
					
					/* Set first variation */
					$this->ProductList[$row['id']]->setFirstVariationId($row['variation_id']);
					$this->ProductList[$row['id']]->setCurrentVariationId($row['variation_id']);
					$this->ProductList[$row['id']]->setCurrentVariationNum($row['varnum']);
					
					$this->ProductList[$row['id']]->Variations[$row['variation_id']] = new ProductVariation;
					$this->ProductList[$row['id']]->Variations[$row['variation_id']]->setId($row['variation_id']);
					$this->ProductList[$row['id']]->Variations[$row['variation_id']]->setProductId($row['id']);
					$this->ProductList[$row['id']]->Variations[$row['variation_id']]->setVarnum($row['varnum']);
					$this->ProductList[$row['id']]->Variations[$row['variation_id']]->setVarTitle($row['var_title']);
					$this->ProductList[$row['id']]->Variations[$row['variation_id']]->setIdentity($row['identity']);
					$this->ProductList[$row['id']]->Variations[$row['variation_id']]->setExtIdentity($row['ext_identity']);
					$this->ProductList[$row['id']]->Variations[$row['variation_id']]->setBuyMin($row['buy_min']);
					/*
					$this->ProductList[$row['id']]->Variations[$row['variation_id']]->setStockCount($row['stock_count']);
					$this->ProductList[$row['id']]->Variations[$row['variation_id']]->setStockAddDate($row['stock_add_date']);
					$this->ProductList[$row['id']]->Variations[$row['variation_id']]->setStockAddQuan($row['stock_add_quan']);
					$this->ProductList[$row['id']]->Variations[$row['variation_id']]->setStockAddTxt($row['stock_add_txt']);
					$this->ProductList[$row['id']]->Variations[$row['variation_id']]->setNetWeight($row['net_weight']);
					$this->ProductList[$row['id']]->Variations[$row['variation_id']]->setGrosWeight($row['gros_weight']);
					*/
					$this->ProductList[$row['id']]->Variations[$row['variation_id']]->setLength($row['length']);
					$this->ProductList[$row['id']]->Variations[$row['variation_id']]->setWidth($row['width']);
					$this->ProductList[$row['id']]->Variations[$row['variation_id']]->setHeight($row['height']);
					
					$this->ProductList[$row['id']]->Variations[$row['variation_id']]->setStdPrice($row['std_price']);
					$this->ProductList[$row['id']]->Variations[$row['variation_id']]->setNowPrice($row['now_price']);
					$this->ProductList[$row['id']]->Variations[$row['variation_id']]->setNowPriceDateEnd($row['NowPriceDateEnd']);
					$this->ProductList[$row['id']]->Variations[$row['variation_id']]->setOfferPrice($row['offer_price']);
					$this->ProductList[$row['id']]->Variations[$row['variation_id']]->setOfferStart($row['offer_start']);
					$this->ProductList[$row['id']]->Variations[$row['variation_id']]->setOfferEnd($row['offer_end']);
					$this->ProductList[$row['id']]->Variations[$row['variation_id']]->setTaxId($this->ProductList[$row['id']]->TaxId);
					$this->ProductList[$row['id']]->Variations[$row['variation_id']]->setTaxValue($this->ProductList[$row['id']]->TaxValue);
					/* Set first variation End */
					$i++;
				}
				self::loadProductListAttVals();
			}
		}
	}
	
	function loadProductListAttVals()
	{
		if(count($this->ProductList) > 0)
		{
			$attr = self::getAttributes();
			if(count($attr) > 0)
			{
				$where = '';
				foreach($this->ProductList as $product)
				{
					if($where == '')
					{ $where = ' product_id='.$product->Id; }
					else
					{ $where .= ' OR product_id='.$product->Id; }
				}
				if($where != '')
				{
					$sql = 'SELECT * FROM '.DB_PERFIX.'product_vals WHERE '.$where.';';
					$result = mysql_query($sql);
					if(mysql_num_rows($result) > 0)
					{
						while($row = mysql_fetch_array($result))
						{
							$this->ProductList[$row['product_id']]->Attributes[$row['attribute_id']]['title'] = $attr[$row['attribute_id']]['title'];
							$this->ProductList[$row['product_id']]->Attributes[$row['attribute_id']]['value'] = $row['value'];
							
							$this->ProductList[$row['product_id']]->Attribute[$row['attribute_id']] = $attr[$row['attribute_id']]['title'];
							$this->ProductList[$row['product_id']]->AttributeValues[$row['attribute_id']] = $row['value'];
						}
					}
				}
			}
		}
	}
	
	function setProductAttVals(&$items, $attr)
	{
		if(($items) && ($attr))
		{
			$where = '';
			foreach ($items as $item)
			{
				if($where == '')
				{ $where = ' product_id='.$item['id']; }
				else
				{ $where .= ' OR product_id='.$item['id']; }
			}
			if($where != '')
			{
				$sql = 'SELECT * FROM '.DB_PERFIX.'product_vals WHERE '.$where.';';
				$result = mysql_query($sql);
				if(mysql_num_rows($result) > 0)
				{
					while($row = mysql_fetch_array($result))
					{
						$items[$row['product_id']]['attributes'][$row['attribute_id']]['title'] = $attr[$row['attribute_id']]['title'];
						$items[$row['product_id']]['attributes'][$row['attribute_id']]['value'] = $row['value'];
					}
				}
			}
		}
	}
	
	function getProduct($id)
	{
		if($id > 0)
		{
			$result = mysql_query('SELECT * FROM '.DB_PERFIX.'product WHERE id='.$id.' LIMIT 1;');
			if(mysql_num_rows($result) > 0)
			{
				while($row = mysql_fetch_array($result))
				{
					foreach(array_keys($row) as $key)
					{ $item[$key] = $row[$key]; }
				}
				return $item;
			}
		}
	}
	
	
	function getProductCats()
	{
		$i=0;
		$result = mysql_query('SELECT * FROM '.DB_PERFIX.'product_cats;');
		if(mysql_num_rows($result) > 0)
		{
			while($row = mysql_fetch_array($result))
			{
				$item[$i]['id'] = $row['id'];
				$item[$i]['title'] = $row['title'];
				$item[$i]['title_import'] = $row['title_import'];
				$item[$i]['active'] = $row['active'];
				$i++;
			}
			return $item;
		}
	}
	
	function getProductSections($parent=0)
	{
		$wheread = '';
		if($parent > 0)
		{ $wheread = ' AND parent_id='.$parent; }
		
		$i=0;
		$result = mysql_query('SELECT * FROM '.DB_PERFIX.'sitemap_pages WHERE site_id='.SITE_ID.' AND link_type=6 AND active=1 '.$wheread.' ORDER BY menu_order, title ASC;');
		if(mysql_num_rows($result) > 0)
		{
			$i = 0;
			while($row = mysql_fetch_array($result))
			{
				foreach(array_keys($row) as $key)
				{ $item[$i][$key] = $row[$key]; }
				$i++;
			}
			return $item;
		}
	}
	
	function getProductGroups()
	{
		$i=0;
		$result = mysql_query('SELECT * FROM '.DB_PERFIX.'product_groups;');
		if(mysql_num_rows($result) > 0)
		{
			while($row = mysql_fetch_array($result))
			{
				$item[$i]['id'] = $row['id'];
				$item[$i]['title'] = $row['title'];
				$item[$i]['title_import'] = $row['title_import'];
				$item[$i]['active'] = $row['active'];
				$i++;
			}
			return $item;
		}
	}
	
	public function recalculateAllVariationsPrice()
	{
		//Do not recalculate first variation
		set_time_limit(360);
		if(isset($this->CurrentProduct))
		{
			if(count($this->CurrentProduct->Variations) > 1)
			{
				foreach(array_keys($this->CurrentProduct->Variations) as $varid)
				{
					if($varid != $this->CurrentProduct->getFirstVariationId())
					{ 
						//echo '<br />self::recalculateVariationPrice('.$varid.')';
						self::recalculateVariationPrice($varid); 
						
					}
				}
			}
		}
	}
	
	public function recalculateVariationPrice($varid=0)
	{
		//Do not recalculate first variation
		set_time_limit(360);
		if((isset($this->CurrentProduct)) && ($varid != $this->CurrentProduct->getFirstVariationId()))
		{
			if(isset($this->CurrentProduct->Variations[$this->CurrentProduct->getFirstVariationId()]))
			{
				self::loadProductAttributes();
				if(($this->CurrentProduct->Variations[$varid]->getAttributes()) && ($this->ProductAttributes))
				{
					$varprice  = $this->CurrentProduct->Variations[$varid]->getStdPrice();
					$baseprice = $this->CurrentProduct->Variations[$this->CurrentProduct->getFirstVariationId()]->getStdPrice();
					$pricediff = 0;
					foreach($this->CurrentProduct->Variations[$varid]->getAttributes() as $attribute)
					{
						if(isset($this->ProductAttributes[$attribute['value']['attribute_id']]->Values[$attribute['value']['value_id']]))
						{
							$attprice = $this->ProductAttributes[$attribute['value']['attribute_id']]->Values[$attribute['value']['value_id']]->getValuePrice();
							if($attprice > 0)
							{ $pricediff = ($pricediff+$attprice); }
						}
					}
					if(($pricediff > 0) || ($varprice != $baseprice))
					{
						$newprice = $baseprice+$pricediff;
						$this->CurrentProduct->Variations[$varid]->setStdPrice($newprice);
						$this->CurrentProduct->Variations[$varid]->setDataChanged(true);
						$this->CurrentProduct->Variations[$varid]->update();
					}
				}
			}
		}
	}
	
	function loadProductAttributes($id=0)
	{
		if(self::getProductAttributesLoaded() == false)
		{
			$loadPredefVals = false;
			self::setProductAttributesLoaded(true);
			if($id > 0)
			{ $select = 'SELECT * FROM '.DB_PERFIX.'product_attributes WHERE id='.$id.';'; }
			else
			{ $select = 'SELECT * FROM '.DB_PERFIX.'product_attributes;'; }
			$result = mysql_query($select);
			if(mysql_num_rows($result) > 0)
			{
				$i=0;
				while($row = mysql_fetch_array($result))
				{
					$this->ProductAttributes[$row['id']] = new ProductAttribute;
					$this->ProductAttributes[$row['id']]->setId($row['id']);
					$this->ProductAttributes[$row['id']]->setType($row['type']);
					$this->ProductAttributes[$row['id']]->setTitle($row['title']);
					$this->ProductAttributes[$row['id']]->setTitleImport($row['title_import']);
					$this->ProductAttributes[$row['id']]->setEffect($row['effect']);
					$this->ProductAttributes[$row['id']]->setEffectImage($row['effect_image']);
					$this->ProductAttributes[$row['id']]->setPredefined($row['predefined']);
					$this->ProductAttributes[$row['id']]->setDisplay($row['display']);
					$this->ProductAttributes[$row['id']]->setDisplayList($row['display_list']);
					$this->ProductAttributes[$row['id']]->setDisplayAll($row['display_all']);
					$this->ProductAttributes[$row['id']]->setValTypes($row['val_types']);
					$this->ProductAttributes[$row['id']]->setActive($row['active']);
					$this->ProductAttributes[$row['id']]->setTaxId(self::getGlobalSetting('default_tax_id'));
					$this->ProductAttributes[$row['id']]->setTaxValue(self::getGlobalSetting('default_tax_value'));
								
					if((self::getCurrentAttributeId() > 0) && (self::getCurrentAttributeId() == $row['id']))
					{ $this->CurrentAttribute = $this->ProductAttributes[$row['id']]; }
					
					if($id > 0)
					{
						foreach(array_keys($row) as $key)
						{ $items[$key] = $row[$key]; }
					}
					else
					{
						foreach(array_keys($row) as $key)
						{ $items[$row['id']][$key] = $row[$key]; }
					}
				}
				if($items)
				{
					foreach($items as $item)
					{
						if($item['predefined'] = 1)
						{ $loadPredefVals = true; }
					}
					if($loadPredefVals == true)
					{
						if($id > 0)
						{ $select = 'SELECT * FROM '.DB_PERFIX.'product_attribute_values WHERE attribute_id='.$id.' ORDER BY value_order, id ASC;'; }
						else
						{ $select = 'SELECT * FROM '.DB_PERFIX.'product_attribute_values ORDER BY value_order, id ASC;'; }
						$result = mysql_query($select);
						if(mysql_num_rows($result) > 0)
						{
							while($row = mysql_fetch_array($result))
							{
								$this->ProductAttributes[$row['attribute_id']]->Values[$row['id']] = new ProductAttributeValue();
								$this->ProductAttributes[$row['attribute_id']]->Values[$row['id']]->setId($row['id']);
								$this->ProductAttributes[$row['attribute_id']]->Values[$row['id']]->setAttributeId($row['attribute_id']);
								$this->ProductAttributes[$row['attribute_id']]->Values[$row['id']]->setValue($row['value']);
								$this->ProductAttributes[$row['attribute_id']]->Values[$row['id']]->setPostfix($row['postfix']);
								$this->ProductAttributes[$row['attribute_id']]->Values[$row['id']]->setPostfixPosition($row['postfix_position']);
								$this->ProductAttributes[$row['attribute_id']]->Values[$row['id']]->setValuePrice($row['value_price']);
								$this->ProductAttributes[$row['attribute_id']]->Values[$row['id']]->setValueOrder($row['value_order']);
								$this->ProductAttributes[$row['attribute_id']]->Values[$row['id']]->setActive($row['active']);
								$this->ProductAttributes[$row['attribute_id']]->Values[$row['id']]->setVisible($row['visible']);
								$this->ProductAttributes[$row['attribute_id']]->Values[$row['id']]->setTaxId(self::getGlobalSetting('default_tax_id'));
								$this->ProductAttributes[$row['attribute_id']]->Values[$row['id']]->setTaxValue(self::getGlobalSetting('default_tax_value'));
								
								foreach(array_keys($row) as $key)
								{ $this->ProductAttributes[$row['attribute_id']]->ValuesArray[$row['id']][$key] = $row[$key]; }
								$this->ProductAttributes[$row['attribute_id']]->setValuesLoaded(true);
							
								if((self::getCurrentAttributeId() > 0) && (self::getCurrentAttributeId() == $row['attribute_id']))
								{ $this->CurrentAttribute = $this->ProductAttributes[$row['attribute_id']]; }
					
								if($id > 0)
								{
									foreach(array_keys($row) as $key)
									{ $items['predefined_values'][$row['id']][$key] = $row[$key]; }
								}
								else
								{
									foreach(array_keys($row) as $key)
									{ $items[$row['attribute_id']]['predefined_values'][$row['id']][$key] = $row[$key]; }
								}
							}
						}
					}
				}
				return $items;
			}
		}
	}
	
	function getShopCats($id=0)
	{
		if($id > 0)
		{ $select = 'SELECT id, title FROM '.DB_PERFIX.'product_cats WHERE id='.$id.';'; }
		else
		{ $select = 'SELECT id, title FROM '.DB_PERFIX.'product_cats;'; }
		$result = mysql_query($select);
		if(mysql_num_rows($result) > 0)
		{
			while($row = mysql_fetch_array($result))
			{
				foreach(array_keys($row) as $key)
				{ $item[$row['id']][$key] = $row[$key]; }
			}
			return $item;
		}
	}
	
	function loadCats($id=0)
	{
		if(!self::getItemLoaded('ShopCats'))
		{
			global $db;
			
			if($id > 0)
			{ $sql = 'SELECT * FROM '.DB_PERFIX.'product_cats WHERE id='.$id.';'; }
			else
			{ $sql = 'SELECT * FROM '.DB_PERFIX.'product_cats;'; }
			
			$result = $db->query($sql);
			$data = $db->fetch($sql, CACHE_TTL);
			
			if(is_array($data))
			{
				foreach($data as $row)
				{
					$this->Cats[$row['id']] = new ProductCat();
					$this->Cats[$row['id']]->setId($row['id']);
					$this->Cats[$row['id']]->setTitle($row['title']);
					$this->Cats[$row['id']]->setTitleImport($row['title_import']);
					$this->Cats[$row['id']]->setActive($row['active']);
				}
			}
			self::setItemLoaded('ShopCats', true);
		}
		if(($id > 0) && (isset($this->Cats[$id])))
		{ return $this->Cats[$id]; }
	}
	
	function loadGroups($id=0)
	{
		if(!self::getItemLoaded('ShopGroups'))
		{
			global $db;
			
			if($id > 0)
			{ $sql = 'SELECT * FROM '.DB_PERFIX.'product_groups WHERE id='.$id.';'; }
			else
			{ $sql = 'SELECT * FROM '.DB_PERFIX.'product_groups ORDER BY title ASC;'; }
			
			$result = $db->query($sql);
			$data = $db->fetch($sql, CACHE_TTL);
			
			if(is_array($data))
			{
				foreach($data as $row)
				{
					$this->Groups[$row['id']] = new ProductGroup();
					$this->Groups[$row['id']]->setId($row['id']);
					$this->Groups[$row['id']]->setTitle($row['title']);
					$this->Groups[$row['id']]->setTitleImport($row['title_import']);
					$this->Groups[$row['id']]->setActive($row['active']);
					
					if((self::getCurrentGroupId() > 0) && (self::getCurrentGroupId() == $row['id']))
					{ $this->CurrentGroup = $this->Groups[$row['id']]; }
				}
			}
			unset($data);
			self::setItemLoaded('ShopGroups', true);
			if(self::getCurrentGroup())
			{ $this->CurrentGroup->loadProviders(); }
		}
		if(($id > 0) && (isset($this->Groups[$id])))
		{ return $this->Groups[$id]; }
	}
	
	function loadTaxGroups($id=0)
	{
		if($id > 0)
		{ $select = 'SELECT id, title, tax FROM '.DB_PERFIX.'shop_tax WHERE id='.$id.';'; }
		else
		{ $select = 'SELECT id, title, tax FROM '.DB_PERFIX.'shop_tax WHERE site_id='.self::getSiteId().' ORDER BY is_default DESC;'; }
		$result = mysql_query($select);
		if(mysql_num_rows($result) > 0)
		{
			while($row = mysql_fetch_array($result))
			{
				foreach(array_keys($row) as $key)
				{ $this->TaxGroups[$row['id']][$key] = $row[$key]; }
			}
		}
	}
	
	function loadCurrencies($iso='')
	{
		if(!self::getItemLoaded('Currencies'.$iso))
		{
			global $db;
			if($iso != '')
			{ $sql = 'SELECT * FROM '.DB_PERFIX.'currency WHERE iso = "'.$iso.'";'; }
			else
			{ $sql = 'SELECT * FROM '.DB_PERFIX.'currency WHERE active=1 ORDER BY currencyOrder ASC;'; }
			
			$result = $db->query($sql);
			$data = $db->fetch($sql, CACHE_TTL);
	
			if(is_array($data))
			{
				foreach($data as $row)
				{
					foreach(array_keys($row) as $key)
					{ $this->Currencies[$row['iso']][$key] = $row[$key]; }
				}
			}
			self::setItemLoaded('Currencies'.$iso, 1);
		}
	}
	
	function loadProviders($id=0)
	{
		if(!self::getItemLoaded('Providers'))
		{
			global $db;
			if(self::getFrontend())
			{
				if($id > 0)
				{ $sql = 'SELECT * FROM '.DB_PERFIX.'product_providers WHERE id='.$id.' AND active=1;'; }
				else
				{ $sql = 'SELECT * FROM '.DB_PERFIX.'product_providers WHERE active=1 ORDER BY title ASC;'; }
			}
			else
			{
				if($id > 0)
				{ $sql = 'SELECT * FROM '.DB_PERFIX.'product_providers WHERE id='.$id.';'; }
				else
				{ $sql = 'SELECT * FROM '.DB_PERFIX.'product_providers;'; }
			}
			
			$result = $db->query($sql);
			$data = $db->fetch($sql, CACHE_TTL);
			
			if(is_array($data))
			{
				foreach($data as $row)
				{
					$this->Providers[$row['id']] = new Provider();
					$this->Providers[$row['id']]->setId($row['id']);
					$this->Providers[$row['id']]->setTitle($row['title']);
					$this->Providers[$row['id']]->setTitleImport($row['title_import']);
					$this->Providers[$row['id']]->setContact($row['contact']);
					$this->Providers[$row['id']]->setAddress($row['address']);
					$this->Providers[$row['id']]->setZip($row['zip']);
					$this->Providers[$row['id']]->setCity($row['city']);
					$this->Providers[$row['id']]->setCountry($row['country']);
					$this->Providers[$row['id']]->setTel($row['tel']);
					$this->Providers[$row['id']]->setFax($row['fax']);
					$this->Providers[$row['id']]->setEmail($row['email']);
					$this->Providers[$row['id']]->setHomepage($row['homepage']);
					$this->Providers[$row['id']]->setDescription($row['description']);
					$this->Providers[$row['id']]->setActive($row['active']);
					
					if((self::getCurrentProviderId() > 0) && (self::getCurrentProviderId() == $row['id']))
					{ $this->CurrentProvider = $this->Providers[$row['id']]; }
				}
			}
			unset($data);
			self::setItemLoaded('Providers', true);
			
		}
		if(($id > 0) && (isset($this->Providers[$id])))
		{ return $this->Providers[$id]; }
	}
	
	function loadBrands($id=0)
	{
		if(!self::getItemLoaded('Brands'))
		{
			global $db;
			
			if($id > 0)
			{ $sql = 'SELECT * FROM '.DB_PERFIX.'product_brands WHERE id='.$id.' ORDER BY title ASC;'; }
			else
			{ $sql = 'SELECT * FROM '.DB_PERFIX.'product_brands ORDER BY title ASC;'; }
			
			$result = $db->query($sql);
			$data = $db->fetch($sql, CACHE_TTL);
			
			if(is_array($data))
			{
				foreach($data as $row)
				{
					$this->Brands[$row['id']] = new ProductBrand();
					$this->Brands[$row['id']]->setId($row['id']);
					$this->Brands[$row['id']]->setTitle($row['title']);
					$this->Brands[$row['id']]->setTitleImport($row['title_import']);
					$this->Brands[$row['id']]->setCountry($row['country']);
					$this->Brands[$row['id']]->setActive($row['active']);
				}
			}
			unset($data);
			self::setItemLoaded('Brands', true);
		}
		if(($id > 0) && (isset($this->Brands[$id])))
		{ return $this->Brands[$id]; }
	}
	
	function loadShopQuestions($id=0)
	{
		if(!self::getItemLoaded('ShopQuestions'))
		{
			global $db;
			
			if($id > 0)
			{ $sql = 'SELECT * FROM '.DB_PERFIX.'shop_questions WHERE id='.$id.';'; }
			else
			{ $sql = 'SELECT * FROM '.DB_PERFIX.'shop_questions;'; }
			
			$result = $db->query($sql);
			$data = $db->fetch($sql, CACHE_TTL);
			
			if(is_array($data))
			{
				foreach($data as $row)
				{
					$this->ShopQuestions[$row['id']] = new ShopQuestion();
					$this->ShopQuestions[$row['id']]->setId($row['id']);
					$this->ShopQuestions[$row['id']]->setTitle($row['title']);
					$this->ShopQuestions[$row['id']]->setActive($row['active']);
					$this->ShopQuestions[$row['id']]->loadAnswers();
				}
			}
			unset($data);
			self::setItemLoaded('ShopQuestions', true);
		}
		if(($id > 0) && (isset($this->ShopQuestions[$id])))
		{ return $this->ShopQuestions[$id]; }
	}
	
	function loadBrandProviders($id=0)
	{
		if(!self::getItemLoaded('BrandProviders'))
		{
			global $db;
			$sql  = 'SELECT br.title, br.country, br.active, ptb.brand_id, ptb.provider_id, pr.title AS provider_title ';
			$sql .= 'FROM '.DB_PERFIX.'product_brands AS br ';
			$sql .= 'LEFT JOIN '.DB_PERFIX.'product_provider_to_brands AS ptb ON ptb.brand_id=br.id ';
			$sql .= 'LEFT JOIN '.DB_PERFIX.'product_providers AS pr ON ptb.provider_id=pr.id ';
			$sql .= 'WHERE ptb.brand_id > 0 AND ptb.provider_id > 0 ';
			if(self::getView() == 'frontend_list')
			{ $sql .= ' AND br.active=1 AND pr.active=1 '; }
			$sql .= 'ORDER BY br.title ASC;';
			$result = $db->query($sql);
			$data = $db->fetch($sql, CACHE_TTL);
			
			if(is_array($data))
			{
				foreach($data as $row)
				{
					$this->BrandProviders[$row['brand_id']] = new ProductBrand();
					$this->BrandProviders[$row['brand_id']]->setId($row['brand_id']);
					$this->BrandProviders[$row['brand_id']]->setTitle($row['title']);
					$this->BrandProviders[$row['brand_id']]->setCountry($row['country']);
					$this->BrandProviders[$row['brand_id']]->setActive($row['active']);
					$this->BrandProviders[$row['brand_id']]->Providers[$row['provider_id']] = new Provider();
					$this->BrandProviders[$row['brand_id']]->Providers[$row['provider_id']]->setId($row['provider_id']);
					$this->BrandProviders[$row['brand_id']]->Providers[$row['provider_id']]->setTitle($row['provider_title']);
				}
			}
			unset($data);
			self::setItemLoaded('BrandProviders', true);
		}
		if(($id > 0) && (isset($this->BrandProviders[$id])))
		{ return $this->BrandProviders[$id]; }
	}
	
	function getShopShippingMethods($id=0)
	{
		if($id > 0)
		{ $select = 'SELECT * FROM '.DB_PERFIX.'shop_shipping WHERE id='.$id.' AND active=1 AND (site_id='.SITE_ID.' OR site_id=0);'; }
		else
		{ $select = 'SELECT * FROM '.DB_PERFIX.'shop_shipping WHERE active=1 AND (site_id='.SITE_ID.' OR site_id=0);'; }
		$result = mysql_query($select);
		if(mysql_num_rows($result) > 0)
		{
			while($row = mysql_fetch_array($result))
			{
				foreach(array_keys($row) as $key)
				{ $item[$row['id']][$key] = $row[$key]; }
			}
			return $item;
		}
	}
	
	function getShopShippingZones($id=0)
	{
		if($id > 0)
		{ $select = 'SELECT * FROM '.DB_PERFIX.'shop_shipping_zones WHERE id='.$id.';'; }
		else
		{ $select = 'SELECT * FROM '.DB_PERFIX.'shop_shipping_zones;'; }
		$result = mysql_query($select);
		if(mysql_num_rows($result) > 0)
		{
			while($row = mysql_fetch_array($result))
			{
				foreach(array_keys($row) as $key)
				{ $item[$row['id']][$key] = $row[$key]; }
			}
			return $item;
		}
	}
	
	function loadShippingZones($id=0, $parentId=0)
	{
		if(!self::getItemLoaded('ShippingZones'.$id))
		{
			global $db;
			
			$sql = 'SELECT * FROM '.DB_PERFIX.'shop_shipping_zones WHERE id>0 ';
			if($id > 0)
			{ $sql .= ' AND id='.intval($id); }
			if($parentId > 0)
			{ $sql .= ' AND parent_id='.intval($parentId); }
			$sql .= ';';
			
			$result = $db->query($sql);
			$data = $db->fetch($sql, CACHE_TTL);
			
			if(is_array($data))
			{
				foreach($data as $row)
				{
					foreach(array_keys($row) as $key)
					{ $this->ShippingZones[$row['id']][$key] = $row[$key]; }
				}
			}
			self::setItemLoaded('ShippingZones'.$id, true);
		}
	}
	
	public function setForms($key='')
	{
		global $ac;
		switch ($key)
		{
			case 'new_user':
			case 'customer':
			case 'alternate_delivery':
			case 'new_user_quick':
				$this->Forms[$key] = $ac->getForms($key);
				$this->Forms[$key]->HumanCheck = 0;
			break;
		}
	}
	
	function deleteOrder($id=0)
	{
		$id = intval($id);
		if((self::getOrders()) && ($id > 0))
		{
			if(isset($this->Orders[$id]))
			{
				$delete = 'DELETE FROM '.DB_PERFIX.'shop_order_items WHERE order_id='.$id.';';
				$result = mysql_query($delete);
				$delete = 'DELETE FROM '.DB_PERFIX.'shop_orders WHERE id='.$id.';';
				$result = mysql_query($delete);
				if(is_file(ORDERS_PATH.'order_'.$id.'_confirmation.html'))
				{ unlink(ORDERS_PATH.'order_'.$id.'_confirmation.html'); }
				unset($this->Orders[$id]);
				return true;
			}
		}
	}
	
	public function changeOrderDeliveryStatus($id, $toStatus=0)
	{
		$id = intval($id);
		$toStatus = intval($toStatus);
		$info['sucess'] = false;
		
		if(($id > 0) && ($toStatus > 0) && (self::getOrder($id)))
		{
			if(isset($this->Orders[$id]))
			{
				if($toStatus != $this->Orders[$id]->getDeliveryStatus())
				{
					/* DIBS Card Payment */
					if($this->Orders[$id]->getPaymentID() == 2)
					{
						$dibs = new PaymentDIBS();
						if($toStatus == 1)
						{
							$response = $dibs->reauthorizeOrder($this->Orders[$id]);
							if($response['statuscode'] == true)
							{ 
								$this->Orders[$id]->setDeliveryStatus($toStatus);
								$info['info'] = $response['info'];
							}
							else
							{ $info['error'] = $response['error']; }
							
						}
						if($toStatus == 2)
						{
							$response = $dibs->reauthorizeOrder($this->Orders[$id]);
							if($response['statuscode'] == true)
							{ 
								unset($response);
								$response = $dibs->captureOrder($this->Orders[$id]);
								if(($response['statuscode'] == true) && (intval($response['statustxt']) == 0))
								{
									$this->Orders[$id]->setPaymentStatus(2); 
									$this->Orders[$id]->setDeliveryStatus($toStatus); 
									$this->Orders[$id]->setDateDelivered(date("Y-m-d H:i:s")); 
									$info['info'] = $response['info'];
								}
								else
								{ $info['error'] = $response['error']; }
							}
						}
					}
					/* DIBS Card Payment End*/
					
					/* NETS Card Payment */
					if($this->Orders[$id]->getPaymentID() == 6)
					{
						$nets = new PaymentNETS();
						if($toStatus == 1)
						{
							$response = $nets->GetStatus($this->Orders[$id]);
							//print_r($response);
							if(is_object($response))
							{ 
								if($response->Summary->Authorized = 1)
								{
									$this->Orders[$id]->setDeliveryStatus($toStatus);
									$info['info'] = $response;
								}
							}
							else
							{ $info['error'] = $response; }
							
						}
						if($toStatus == 2)
						{
							$response = $nets->GetStatus($this->Orders[$id]);
							if(is_object($response))
							{ 
								if($response->Summary->Authorized = 1)
								{
									unset($response);
									$response = $nets->Capture($this->Orders[$id]);
									if($response == 'OK')
									{
										$this->Orders[$id]->setPaymentStatus(2); 
										$this->Orders[$id]->setDeliveryStatus($toStatus); 
										$this->Orders[$id]->setDateDelivered(date("Y-m-d H:i:s")); 
										$info['info'] = $response;
									}
									else
									{ $info['error'] = $response; }
								}
							}
						}
					}
					/* NETS Card Payment End*/
					
					/* Cash Payment */
					if($this->Orders[$id]->getPaymentID() == 1)
					{
						if($toStatus == 1)
						{ $this->Orders[$id]->setDeliveryStatus($toStatus); }
						if($toStatus == 2)
						{
							$this->Orders[$id]->setPaymentStatus(2); 
							$this->Orders[$id]->setDeliveryStatus($toStatus); 
							$this->Orders[$id]->setDateDelivered(date("Y-m-d H:i:s"));
						}
					}
					/* Cash Payment End*/
					
					if($toStatus == $this->Orders[$id]->getDeliveryStatus()) //Status change sucess
					{ 
						$this->Orders[$id]->setConfirmed(1);
						$this->Orders[$id]->updateOrder();
						$this->Orders[$id]->sendOrderStatusConfirmation();
						$info['sucess'] = true;
						$info['statustxt'] = $response;
					} 
				}
			}
		}
		return $info;
	}
	
	function loadOrders($id=0)
	{
		if(!self::getItemLoaded('Orders'.$id))
		{ 
			global $db;
			global $katana;
			
			if(intval($id) > 0)
			{ $sql 	= 'SELECT * FROM '.DB_PERFIX.'shop_orders WHERE site_id='.$katana->getId().' AND id='.intval($id).';'; }
			else
			{ $sql  = 'SELECT * FROM '.DB_PERFIX.'shop_orders WHERE site_id='.$katana->getId().' AND confirmed=1 AND payment_status>0 ORDER BY date_delivery, date_ordered DESC;'; }
			
			
			$result = $db->query($sql);
			$data = $db->fetch($sql, 0);
			
			if(is_array($data))
			{
				foreach($data as $row)
				{
					$this->Orders[$row['id']] = new Order;
					
					$this->Orders[$row['id']]->setId($row['id']);
					$this->Orders[$row['id']]->setSiteID($row['site_id']);
					$this->Orders[$row['id']]->setUserID($row['user_id']);
					$this->Orders[$row['id']]->setCartSession($row['cart_session']);
					$this->Orders[$row['id']]->setConfirmed($row['confirmed']);
					$this->Orders[$row['id']]->setDoubleConfirm($row['DoubleConfirm']);
					$this->Orders[$row['id']]->setDoubleConfirmed($row['DoubleConfirmed']);
	
					$this->Orders[$row['id']]->setAdId($row['AdId']);
					
					$this->Orders[$row['id']]->setShippingID($row['shipping_id']);
					$this->Orders[$row['id']]->setShippingTitle($row['shipping_title']);
					$this->Orders[$row['id']]->setShippingStatus($row['shipping_status']);
					
					$this->Orders[$row['id']]->setDeliveryStatus($row['delivery_status']);
					
					$this->Orders[$row['id']]->setShippingZoneId($row['shipping_zone_id']);
					$this->Orders[$row['id']]->setShippingZoneCode($row['shipping_zone_code']);
					$this->Orders[$row['id']]->setShippingZoneTitle($row['shipping_zone_title']);
					$this->Orders[$row['id']]->setShippingZoneEmail($row['shipping_zone_email']);
					
					$this->Orders[$row['id']]->setDateOrdered($row['date_ordered']);
					$this->Orders[$row['id']]->setDateDelivery($row['date_delivery']); 
					$this->Orders[$row['id']]->setDateDelivered($row['date_delivered']);
				
					$this->Orders[$row['id']]->setPaymentID($row['payment_id']);
					$this->Orders[$row['id']]->setPaymentTitle($row['payment_title']);
					$this->Orders[$row['id']]->setPaymentStatus($row['payment_status']);
					$this->Orders[$row['id']]->setPaymentTransact($row['payment_transact']);
					
					$this->Orders[$row['id']]->setCostTotal($row['cost_total']);
					$this->Orders[$row['id']]->setCostItems($row['cost_items']);
					$this->Orders[$row['id']]->setCostItemsVat($row['cost_items_vat']);
					$this->Orders[$row['id']]->setCostShipping($row['cost_shipping']);
					$this->Orders[$row['id']]->setCostShippingVat($row['cost_shipping_vat']);
					
					$this->Orders[$row['id']]->setDimUnit($row['dim_unit']);
					$this->Orders[$row['id']]->setWeightUnit($row['weight_unit']);
					$this->Orders[$row['id']]->setVolume($row['volume_total']);
					$this->Orders[$row['id']]->setNetWeight($row['net_weight_total']);
					$this->Orders[$row['id']]->setGrosWeight($row['gros_weight_total']);
					
					$this->Orders[$row['id']]->setAlternateDelivery($row['alternate_delivery']);
					
					$this->Orders[$row['id']]->setBillingName($row['billing_name']);
					$this->Orders[$row['id']]->setBillingLastName($row['billing_last_name']);
					$this->Orders[$row['id']]->setBillingCompany($row['billing_company']);
					$this->Orders[$row['id']]->setBillingEmail($row['billing_email']);
					$this->Orders[$row['id']]->setBillingPhone($row['billing_phone']);
					$this->Orders[$row['id']]->setBillingAddress($row['billing_address']);
					$this->Orders[$row['id']]->setBillingAddress2($row['billing_address2']);
					$this->Orders[$row['id']]->setBillingZip($row['billing_zip']);
					$this->Orders[$row['id']]->setBillingCity($row['billing_city']);
					$this->Orders[$row['id']]->setBillingCountry($row['billing_country']);
					
					$this->Orders[$row['id']]->setDeliveryName($row['delivery_name']);
					$this->Orders[$row['id']]->setDeliveryLastName($row['delivery_last_name']);
					$this->Orders[$row['id']]->setDeliveryAddress($row['delivery_address']);
					$this->Orders[$row['id']]->setDeliveryAddress2($row['delivery_address2']);
					$this->Orders[$row['id']]->setDeliveryZip($row['delivery_zip']);
					$this->Orders[$row['id']]->setDeliveryCity($row['delivery_city']);
					$this->Orders[$row['id']]->setDeliveryCountry($row['delivery_country']);
					$this->Orders[$row['id']]->setDeliveryComment($row['delivery_comment']);
					
					if($row['delivery_status'] == 0) 
					{ $this->OrdersNew[$row['id']] = $this->Orders[$row['id']]; }
					else
					{ 
						if($row['delivery_status'] == 1) 
						{ $this->OrdersPending[$row['id']] = $this->Orders[$row['id']];  }
						else
						{ $this->OrdersProcessed[$row['id']] = $this->Orders[$row['id']]; }
					}
					if((self::getCurrentOrderId() > 0) && (self::getCurrentOrderId() == $row['id']))
					{ $this->CurrentOrder = $this->Orders[$row['id']]; }
				}
			}
			unset($data);
			self::setItemLoaded('Orders'.$id, true);
			self::setOrdersLoaded(true);
		}
	}
	
	public function cronDay()
	{ 
		if(defined('RUN_CRON'))
		{
			//Process orders
			echo 'Shop -> Running cronDay()<br />';
			$pending = self::getOrdersPending();
			$out = 'Pending Orders:'.count($pending).'<br />';
			if(count($pending) > 0)
			{
				//Charge the card if order is set in production
				$sql = 'SELECT id FROM '.DB_PERFIX.'shop_orders WHERE ';
				$sql .= 'confirmed=1 ';
				$sql .= 'AND payment_id=2 ';
				$sql .= 'AND payment_status>0 ';
				$sql .= 'AND delivery_status=1 ';
				$sql .= 'AND date_delivery < "'.date("Y-m-").(intval(date("d"))+1).' 00:00:01" ';
				$sql .= 'AND date_delivery > "'.date("Y-m-d").' 00:00:00" ';
				
				$out .= $sql.'<br />';
				//$sql .= 'AND date_delivery<"'.date("Y-m-").(intval(date("d"))+1).' 00:00:00";';
				
				//echo $sql;
				
				$result = mysql_query($sql); 
				if(mysql_num_rows($result) > 0)
				{
					$i=0;
					while($row = mysql_fetch_array($result))
					{
						if(isset($this->Orders[$row['id']]))
						{ 
							$out .= 'Changing order status for:'.$row['id'].'<br />';
							$info = self::changeOrderDeliveryStatus($row['id'], 2); 
							$out .= $info.'<br />';
							//print_r($info);
						}
					}
				}
				/* Charge card end */
				
				/* Generate delivery orders for next day */
				/* Prebaceno u cronHour()
				/* Generate delivery orders for next day end 2t*/
			}
			if((self::getGlobalSetting('use_currency') > 0) && (self::getGlobalSetting('CurrencyRatesXML') != ''))
			{ $out .= self::updateCurrencyRates(); }
			return $out;
		}
	}
	
	public function cronHour()
	{ 
		if(defined('RUN_CRON'))
		{
			//Process orders
			echo 'Shop -> Running cronHour()<br />';
			$weekday = date("N");
			$hour 	 = date("H");
			echo 'Day:'.$weekday.'<br />';
			echo 'Hour:'.intval($hour).'<br />';
			if(($weekday < 6) && (intval($hour) > 11) && (intval($hour) < 13)) // Furamo ovo samo radnim danima makin sure its 12 midday
			{
				$pending = self::getOrdersPending();
				$out = 'Pending Orders:'.count($pending).'<br />';
				if(count($pending) > 0)
				{	
					/* Generate delivery orders for next day */
					$sql = 'SELECT id FROM '.DB_PERFIX.'shop_orders WHERE ';
					$sql .= 'confirmed=1 ';
					$sql .= 'AND payment_status>0 ';
					$sql .= 'AND delivery_status=1 ';
					$sql .= 'AND DoubleConfirm=0 ';
					$sql .= 'AND shipping_id > 3 ';
					$sql .= 'AND shipping_id < 6 ';
					switch($weekday)
					{
						case 4:
							$after  = mktime(0,0,0,date('m'),date('d')+1,date('Y'));
							$before = mktime(0,0,0,date('m'),date('d')+2,date('Y'));
						break;
						case 5:
							$after  = mktime(0,0,0,date('m'),date('d')+3,date('Y'));
							$before = mktime(0,0,0,date('m'),date('d')+3,date('Y'));
						break;
						default:
							$after  = mktime(0,0,0,date('m'),date('d')+1,date('Y'));
							$before = mktime(0,0,0,date('m'),date('d')+1,date('Y'));
						break;
					}
					$sql .= 'AND date_delivery > "'.date('Y-m-d', $after).' 00:00:00" ';
					$sql .= 'AND date_delivery < "'.date('Y-m-d', $before).' 24:00:00" ';
							
					$result = mysql_query($sql); 
					if(mysql_num_rows($result) > 0)
					{
						$i=0;
						while($row = mysql_fetch_array($result))
						{
							if(isset($this->Orders[$row['id']]))
							{ 
								$sendit = 1;
								$items = $this->Orders[$row['id']]->getOrderItems(); //Izbijanje grupe 3 iz maila
								if($items)
								{
									foreach($items as $item)
									{
										if($item->getGroupId() == 3)
										{ $sendit = 0; }
									}
								}
								if($sendit == 1)
								{ $this->Orders[$row['id']]->sendDeliveryNoticeEmail(); }
							}
						}
					}
					$out .= $sql.'<br />';
				}
				/* Generate delivery orders for next day end 2t*/
			}
			return $out;
		}
	}
	
	public function updateCurrencyRates()
	{
		global $db;
		$importFile = self::getGlobalSetting('CurrencyRatesXML');
		//$importFile = "http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml"; //optional for EUR as base make new function
		$out = 'Updating currency values:<br />Source:'.$importFile.'<br />';
		if (file_get_contents($importFile))
		{
			$update = '';
			$xml = file_get_contents($importFile);
			$feed = simplexml_load_string($xml);
			
			foreach($feed->children() as $currency)
			{  
				$unit = 0;
				$value = 0;
				$update = '';
				$iso = '';
				
				$iso = $currency->isokode;
				$unit = intval($currency->enhet);
				
				if($iso != '')
				{
					foreach($currency->children() as $values)
					{
						if(doubleval($values->midtkurs) > 0)
						{ 
							$value = $values->midtkurs; 
							$value = number_format(doubleval($value), 4);
						}
					}
					
					$sql = 'SELECT * FROM '.DB_PERFIX.'currency WHERE `iso` LIKE "'.$iso.'";';
					
					$result = $db->query($sql);
					$data = $db->fetch($sql, 0);
			
					if(is_array($data))
					{
						foreach($data as $row)
						{
							if($row['iso'] == $iso)
							{
								if(($unit > 0) && ($value != ''))
								{ 
									$update = 'UPDATE `'.DB_PERFIX.'currency` SET `value` = \''.$value.'\', `unit` = '.$unit.' WHERE `iso` LIKE \''.$row['iso'].'\'; ';
									$result = mysql_query($update);
									$out .= 'Updated:'.$row['iso'].' - New value:'.$value.'<br />';
									if($row['active'] > 0)
									{
										$out .= 'Test Conversion of 100: '.self::convertFromCurrency(100, $row['iso'], 2).'<br />';
										$out .= 'Test Conversion of 200: '.self::convertFromCurrency(200, $row['iso'], 2).'<br />';
										$out .= 'Test Conversion of 500: '.self::convertFromCurrency(500, $row['iso'], 0).' - No decimals<br />';
										$out .= 'Test Conversion of 1000: '.self::convertFromCurrency(1000, $row['iso'], 0).' - No decimals<br />';
										
										$out .= 'Test Conversion of 100 (NOK) to '.$row['iso'].': '.self::convertToCurrency(100, $row['iso'], 2).'<br />';
										$out .= 'Test Conversion of 200 (NOK) to '.$row['iso'].': '.self::convertToCurrency(200, $row['iso'], 2).'<br />';
										$out .= 'Test Conversion of 500 (NOK) to '.$row['iso'].': '.self::convertToCurrency(500, $row['iso'], 0).' - No decimals<br />';
										$out .= 'Test Conversion of 1000 (NOK) to '.$row['iso'].': '.self::convertToCurrency(1000, $row['iso'], 0).' - No decimals<br />';
									}
								}
							}
						}
					}
					
					if(($update == '') && ($value != 0) && ($unit > 0) && ($iso != ''))
					{
						$insert  = 'INSERT INTO `'.DB_PERFIX.'currency` (`iso`, `code`, `label`, `label_ba`, `label_no`, `unit`, `value`, `isDefault`, `active`) ';
						$insert .= 'VALUES ("'.$iso.'", "'.$currency->kode.'", "", "", "'.$currency->navn.'", '.$unit.', '.$value.', 0, 0);';
						$result = mysql_query($insert);
						$out .= 'Added currency:'.$currency->kode.' - Unit:'.$unit.' - Value:'.$value.'<br />';
					}
				}
			}
		}
		return $out;
	}
}
?>